<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRefs"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="学校名称" prop="schoolId">
        <el-select
          @change="schoolChange"
          v-model.trim="formData.schoolId"
          clearable
          placeholder="请选择学校"
          filterable
        >
          <el-option
            v-for="item in schoolList"
            :key="item.id"
            :label="item.schoolName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机构名称" prop="collegeId">
        <el-select
          @change="collegeChange"
          v-model.trim="formData.collegeId"
          clearable
          placeholder="请选择机构"
          filterable
        >
          <el-option
            v-for="item in collegeList"
            :key="item.id"
            :label="item.collegeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业名称" prop="majorId">
        <el-select
          @change="changeMajor"
          v-model.trim="formData.majorId"
          clearable
          filterable
          placeholder="请选择专业"
        >
          <el-option
            v-for="item in majorList"
            :key="item.id"
            :label="item.majorName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级名称" prop="classesId">
        <el-select
          @change="classesChange"
          v-model.trim="formData.classesId"
          clearable
          placeholder="请选择班级"
          :disabled="!formData.schoolId"
          filterable
        >
          <el-option
            v-for="item in classesList"
            :key="item.id"
            :label="item.classesName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="老师姓名" prop="teacherId">
        <el-select
          v-model.trim="formData.teacherId"
          clearable
          placeholder="请选择老师"
          filterable
          :disabled="!formData.schoolId"
        >
          <el-option
            v-for="item in teacherList"
            :key="item.id"
            :label="item.teacherName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户名" prop="usernameColumn">
        <el-select v-model="formData.usernameColumn" placeholder="请选择">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_USERNAME_COLUMN)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <GenerateResultTableDialog ref="generateResultTableDialog" />
</template>
<script lang="ts" name="SystemUserForm" setup>
import * as UserApi from '@/api/system/user'
import * as TeacherApi from '@/api/cmis/teacher'
import * as MajorApi from '@/api/cmis/major'
import * as CollegeApi from '@/api/cmis/college'
import * as ClassesApi from '@/api/cmis/classes'
import * as SchoolApi from '@/api/cmis/school'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

const { t } = useI18n() // 国际化
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  schoolId: undefined,
  collegeId: undefined,
  majorId: undefined,
  classesId: undefined,
  teacherId: undefined,
  usernameColumn: undefined
})
const formRules = reactive({
  schoolId: [{ required: true, message: '学校不能为空', trigger: 'blur' }],
  usernameColumn: [{ required: true, message: '用户名不能为空', trigger: 'blur' }]
})
const formRefs = ref() // 表单 Ref
const schoolList = ref([]) //学校列表
const collegeList = ref([]) //机构列表
const majorList = ref([]) //专业列表
const classesList = ref([]) //机构列表
const teacherList = ref([]) //机构列表

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  dialogTitle.value = t('集体新增')
  resetForm()
  // 加载学校列表
  schoolList.value = await SchoolApi.getSchoolList('')
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const schoolChange = async (value: any) => {
  formData.value.collegeId = undefined
  formData.value.majorId = undefined
  formData.value.classesId = undefined
  formData.value.teacherId = undefined

  if (value) {
    // 加载学校列表并开启选择
    collegeList.value = await CollegeApi.getCollegeList(formData.value)
    classesList.value = await ClassesApi.getClassesList(formData.value)
    teacherList.value = await TeacherApi.getTeacherList(formData.value)
    getMajorList()
  }
}

const collegeChange = async () => {
  formData.value.majorId = undefined
  formData.value.classesId = undefined
  formData.value.teacherId = undefined

  // 加载机构列表并开启选择
  classesList.value = await ClassesApi.getClassesList(formData.value)
  teacherList.value = await TeacherApi.getTeacherList(formData.value)
  getMajorList()
}

// 选择专业
const changeMajor = async () => {
  formData.value.classesId = undefined
  formData.value.teacherId = undefined

  // 加载机构列表并开启选择
  classesList.value = await ClassesApi.getClassesList(formData.value)
  teacherList.value = await TeacherApi.getTeacherList(formData.value)
}

const classesChange = async () => {
  formData.value.teacherId = undefined

  // 加载班级列表并开启选择
  teacherList.value = await TeacherApi.getTeacherList(formData.value)
}

const getMajorList = async () => {
  const res = await MajorApi.getMajorList({
    schoolId: formData.value.schoolId,
    collegeId: formData.value.collegeId
  })
  majorList.value = res
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRefs.value) return
  const valid = await formRefs.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as UserApi.TeacherUserVO
    const res = await UserApi.generateTeacherUser(data)
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    openGenerateResultTableDialog(res)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    schoolId: undefined,
    collegeId: undefined,
    majorId: undefined,
    classesId: undefined,
    teacherId: undefined,
    usernameColumn: 1
  }
  formRefs.value?.resetFields()
}

/**
 * 生成后回显的内容
 */
const labelMap = ref({
  teacherName: '老师姓名',
  teacherCode: '老师编号',
  msg: '信息'
})
const generateResultTableDialog = ref()
const openGenerateResultTableDialog = (res) => {
  generateResultTableDialog.value.open(labelMap.value, res)
}
</script>
